﻿using System;
using System.IO;

//Modified and Copied  from :
//http://www.codeproject.com/Articles/2680/Writing-custom-NET-trace-listeners

namespace Util.Tracer {

    public class Tracer : System.Diagnostics.TextWriterTraceListener {
        string _fileName;
        DateTime _currentDate;
        public StreamWriter _traceWriter;

        public Tracer(string fileName) {
            _fileName = fileName;
            _traceWriter = new StreamWriter(generateFilename(), true);
        }

        public override void Write(string value) {
            checkRollover();
            _traceWriter.Write(value);
        }
        public override void WriteLine(string value) {
            checkRollover();
            _traceWriter.WriteLine(DateTime.Now.ToString() +" " + value);
            _traceWriter.Flush();
        }

        private string generateFilename() {
            _currentDate = DateTime.Today;
            if (!Directory.Exists(Path.GetDirectoryName(_fileName)))
                Directory.CreateDirectory(Path.GetDirectoryName(_fileName));
            return Path.Combine(
                Path.GetDirectoryName(_fileName),_currentDate.ToString("yyyy-MM-dd") + "."+ Path.GetFileName(_fileName) );
        }

        public void checkRollover() {
            if (_currentDate.CompareTo(DateTime.Today) != 0) {
                _traceWriter.Close();
                _traceWriter = new StreamWriter(generateFilename(), true);
            }
        }

        protected override void Dispose(bool disposing) {
            if (disposing) {
                _traceWriter.Close();
            }
        }

    }

}